package com.library.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

public class ConnectDb {


	public String validateLogin(String uname, String pwd) throws SQLException {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet result = null;
		String sql = "SELECT * FROM user where UserName = ? and Password = ?";

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "root");
			statement = connection.prepareStatement(sql);
			statement.setString(1, uname);
			statement.setString(2, pwd);

			result = statement.executeQuery();

			if (result.first()) {
				String successful = "Login Successful";
				return successful;
			} else {
				String unSuccessful = "Invalid Username or Password";
				return unSuccessful;
			}
		} catch (Exception e) {
			String exception = e.getMessage();
			return exception;
		}

		finally {
			/* result.close(); */
			statement.close();
			connection.close();
		}

	}

	public String registerUser(String uname, String pwd) throws SQLException {
		Connection connection = null;
		PreparedStatement statement = null;
		
		String sql = "INSERT INTO user(UserName,Password) VALUES(?,?)";

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "root");
			statement = connection.prepareStatement(sql);
			statement.setString(1, uname);
			statement.setString(2, pwd);

		statement.execute();
        String successful = " Registration Successful";
				return successful;
		}catch(SQLIntegrityConstraintViolationException e){
			
			return "Username already exists, try another.";
			
		}
		catch (Exception e) {
			String exception = e.getMessage();
			return exception;
		}

		finally {
			/* result.close(); */
			statement.close();
			connection.close();
		}
		

	}
}
